<?php

namespace app\modules\admin\controllers;

use app\models\Agent;
use app\models\AgentConfig;
use app\models\AgentLog;
use app\models\AgentPackage;
use app\models\Card;
use app\models\KeyMap;
use app\models\ManagerLog;
use app\models\Package;
use app\models\User;
use app\models\UserBill;
use app\models\AgentBill;
use app\models\UserConfig;
use app\models\AgentAccount;
use app\models\UserAccount;
use app\models\UserLog;
use app\models\UserPackage;
use app\models\MoneyChange;
use app\models\Util;
use app\models\BindImei;
use app\models\OrderForm;
use app\models\Order;
use app\models\OutboundForm;
use app\models\Outbound;
use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * 用户管理
 * Class UserController
 * @package app\models
 */
class UserController extends BaseController
{
    /**
     * 代理商列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionAgentList()
    {
        if (!$this->manager->can('user/agent-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = Agent::find();
        $query->andFilterWhere(['id'=>$this->get('search_id')]);
        $query->andFilterWhere(['username'=>$this->get('search_username')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $agentList = $query->all();
        $money = '0';
        return $this->render('agent_list', [
            'agentList' => $agentList,
            'money'     => $money,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 添加修改代理商
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws Exception
     */
    public function actionAgentEdit()
    {
        if (!$this->manager->can('user/agent-edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        if (!empty($id)) {
            $agent = Agent::findOne(['id' => $id]);
            if (empty($agent)) {
                throw new NotFoundHttpException('没有找到代理商信息。');
            }
        } else {
            $agent = new Agent();
            $agent->status = Agent::STATUS_OK;
            $agent->create_time = time();
        }
        if ($agent->load($this->post())) {
            if (!empty($agent->password) && !preg_match('/^\$2y/', $agent->password)) {
                $agent->password = Yii::$app->security->generatePasswordHash($agent->password);
            }
            if(empty($agent->password)){
                $agent->password = $password;
            }
            if ($agent->save()) {
                ManagerLog::info($this->manager->id, '保存代理商', print_r($agent->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/admin/user/agent-list']),
                    'txt' => '代理商列表'
                ]));
                
				if(!$id){
                    $agent_id = $agent->attributes['id'];
					$rt = AgentConfig::setConfig($agent_id, 'comm_agent', '0');
                    /**$package = Package::find()->where(['exception'=>1])->all();
                    foreach ($package as $key => $value) {
                        $agent_package = new AgentPackage();
                        $agent_package->agent_id = $agent_id;
                        $agent_package->package_id = $package[$key]['id'];
                        $agent_package->cost_price = $package[$key]['price'];
                        $agent_package->sale_price = $package[$key]['price'];
                        $agent_package->name = $package[$key]['name'];
                        $agent_package->xuzhi = $package[$key]['xuzhi'];
                        $agent_package->isp = $package[$key]['isp'];
                        $agent_package->save();
                    } */  
                }
                
            }

        }
        return $this->render('agent_edit', [
            'agent' => $agent,
        ]);
    }

    /**
     * 代理商详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentView()
    {
        if (!$this->manager->can('user/agent-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        $cardCount = Card::find()->where(['agent_id'=>$id])->count();
        if (empty($agent)) {
            throw new NotFoundHttpException('没有找到代理商信息。');
        }
        return $this->render('agent_view', [
            'agent' => $agent,
            'cardCount' => $cardCount
        ]);
    }

    /**
     * 重置代理商密码AJAX接口
     * @return array
     * @throws Exception
     */
    public function actionResetAgentPassword()
    {
        if (!$this->manager->can('user/agent-edit')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        if (empty($agent)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        $password = Util::randomStr(6, 1);
        $agent->password = Yii::$app->security->generatePasswordHash($password);
        $agent->save(false);
        ManagerLog::info($this->manager->id, '重置代理商密码', $agent->id);
        return ['new_password' => $password];
    }

    /**
     * 代理商设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentConfig()
    {
        if (!$this->manager->can('user/agent-edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        if (empty($agent)) {
            throw new NotFoundHttpException('没有找到代理商。');
        }
        return $this->render('agent_config', [
            'agent' => $agent,
        ]);
    }

    /**
     * 保存代理商配置AJAX接口
     * @return array
     */
    public function actionSaveAgentConfig()
    {
        if (!$this->manager->can('user/agent-edit')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $agentId = $this->get('agent_id');
        $k = $this->get('k');
        $v = $this->get('v');
		$kt = $this->get('kt');
        $vt = $this->get('vt');
        $agent = Agent::find()
                ->andWhere(['id' => $agentId])
                ->one();
        if (empty($agent)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        if (empty($k)) {
            return ['error' => 'SERVER', 'message' => '参数错误，没有找到键。'];
        }
        $r = AgentConfig::setConfig($agent->id, $k, $v);
		$rt = AgentConfig::setConfig($agent->id, $kt, $vt);
        if (!$r) {
            return ['error' => 'SERVER', 'message' => '无法保存代理商配置。'];
        }
		if (!$rt) {
            return ['error' => 'SERVER', 'message' => '无法保存代理商配置。'];
        }
		
		$query = AgentConfig::find();
		$query->andWhere(['agent_id' => $agent->getSubAidList()]);
		$query->orderBy('id DESC');
		foreach ($query->each() as $comm) {
			if ($vt == 0) {
				AgentConfig::setConfig($comm->agent_id, 'comm_agent', '0');
			}
			if ($vt == 1) {
				AgentConfig::setConfig($comm->agent_id, 'comm_agent', '2');
			}
			if ($vt == 2) {
				AgentConfig::setConfig($comm->agent_id, 'comm_agent', '2');
			}
		}
		
        ManagerLog::info($this->manager->id, '保存代理商配置', print_r($this->get(), true));
        return [];
    }

    /**
     * 代理商日志
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionAgentLogList()
    {
        if (!$this->manager->can('user/agent-log')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = AgentLog::find()->alias('log');
        $query->joinWith('agent agent');
        $query->andFilterWhere(['like', 'agent.username', $this->get('search_username')]);
        $query->andFilterWhere(['log.type' => $this->get('search_type')]);
        $query->andFilterWhere(['like', 'log.info', $this->get('search_info')]);
        $search_start_date = $this->get('search_start_date');
        if (!empty($search_start_date)) {
            $query->andFilterWhere(['>=', 'log.time', strtotime($search_start_date)]);
        }
        $search_end_date = $this->get('search_end_date');
        if (!empty($search_end_date)) {
            $query->andFilterWhere(['<', 'log.time', strtotime($search_end_date) + 86400]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('log.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $logList = $query->all();
        return $this->render('agent_log_list', [
            'logList' => $logList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 代理商日志详情AJAX接口
     * @return array
     */
    public function actionAgentLogDetail()
    {
        if (!$this->manager->can('user/agent-log')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $id = $this->get('id');
        $log = AgentLog::findOne(['id' => $id]);
        if (empty($log)) {
            return ['error' => 'SERVER', 'message' => '没有找到日志信息。'];
        }
        return [
            'log' => $log->getAttributes(['id', 'info', 'time', 'data']),
        ];
    }

    /**
     * 代理商套餐设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentPackage()
    {
        if (!$this->manager->can('user/agent-package')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $agent = Agent::findOne(['id' => $this->get('agent_id')]);
        if (empty($agent)) {
            throw new NotFoundHttpException('没有找到代理商。');
        }
        if (empty($agent->pid)) { // 顶级代理商直接获取系统套餐
            $packageList = Package::find()->all();
        } else { // 获取上级代理商的套餐
            $packageList = [];
            /** @var AgentPackage $parentAgentPackage */
            foreach (AgentPackage::find()->andWhere(['agent_id' => $agent->pid])->each() as $parentAgentPackage) {
                $packageList[] = $parentAgentPackage->package;
            }
        }
        $agentPackageMap = [];
        /** @var AgentPackage $agentPackage */
        foreach (AgentPackage::find()->andWhere(['agent_id' => $agent->id])->each() as $agentPackage) {
            $agentPackageMap[$agentPackage->package_id] = $agentPackage;
            
        }
        return $this->render('agent_package', [
            'agent' => $agent,
            'packageList' => $packageList,
            'agentPackageMap' => $agentPackageMap,

        ]);
    }

    /**
     * 保存代理商价格AJAX接口
     * @return array
     */
    public function actionSaveAgentPackage()
    {
        if (!$this->manager->can('user/agent-package')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $agentId = $this->get('agent_id');
        $packageId = $this->get('package_id');
        $activeReward = $this->get('active_reward');
        $costPrice = $this->get('cost_price');
		$salePrice = $this->get('sale_price');
		$name = $this->get('name');

        $agent = Agent::findOne(['id' => $agentId]);
        if (empty($agent)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        $package = Package::findOne(['id' => $packageId]);
        if (empty($package)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
		if (empty($salePrice)) {
            $salePrice = $package->price;
        }
        if (empty($costPrice) || $costPrice < $package->isp_price) {
            return ['error' => 'SERVER', 'message' => '价格错误。'];
        }
		if ($salePrice < $costPrice) {
            return ['error' => 'SERVER', 'message' => '价格错误,不能低于代理成本价。'];
        }
        $agentPackage = AgentPackage::findOne(['agent_id' => $agent->id, 'package_id' => $package->id]);
        if (empty($agentPackage)) {
            $agentPackage = new AgentPackage();
            $agentPackage->agent_id = $agent->id;
            $agentPackage->package_id = $package->id;
			$agentPackage->isp = $package->isp;
			$agentPackage->xuzhi = $package->xuzhi;
        }
        //$agentPackage->use_pool = $usePool;
        $agentPackage->cost_price = $costPrice;
        $agentPackage->sale_price = $salePrice;
        $agentPackage->active_reward = $activeReward;
        $agentPackage->name = $name;
        $agentPackage->save();

        ManagerLog::info($this->manager->id, '保存代理商价格', print_r($this->get(), true)); return [];
    }
    //删除代理商套餐
    public function actionDeleteAgentPackage()
    {
        if (!$this->manager->can('user/agent-package')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent_id = $this->get('agent_id');
        $agentPackage = AgentPackage::findOne(['package_id' => $id,'agent_id' => $agent_id]);
        $model = AgentPackage::findOne(['id'=>$agentPackage['id']]);
        if (empty($model)) {
            return ['error' => 'SERVER','message' => '没有找到该代理套餐'];
        }try{
            $model->delete();
            return [];
        }catch (\Throwable $e){
        }
        if ($model->delete()) {
            ManagerLog::info($this->manager->id, '删除代理商套餐', print_r($model->attributes, true)); 
        }
        
    }
    /**
     * 用户列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserList()
    {
        if (!$this->manager->can('user/user-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = User::find();
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $userList = $query->all();
        return $this->render('user_list', [
            'userList' => $userList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 用户账单列表
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionBillList()
    {
        if (!$this->manager->can('user/bill-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $user = User::findOne(['id' => $this->get('id')]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户。');
        }

        $query = UserBill::find();
        $query->andWhere(['uid' => $user->id]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('month DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $billList = $query->all();

        return $this->render('bill_list', [
            'user' => $user,
            'billList' => $billList,
            'pagination' => $pagination,
        ]);
    }
    //代理商账单列表
    public function actionCommissionList(){
        $agent = Agent::findOne(['id'=>$this->get('id')]);
        if(empty($agent)){
            throw new Exception("没有找到用户。");
            
        }
        $query = AgentBill::find();
        $query->andWhere(['agent_id'=>$agent->id]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('day DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $commissionList = $query->all();
        return $this->render('commission_list',[
            'agent' => $agent,
            'commissionList' => $commissionList,
            'pagination' => $pagination,
        ]);
    }
    /**
     * 修改用户账单金额AJAX接口
     * @return array
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionModifyBillMoney()
    {
        if (!$this->manager->can('user/bill-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $bill = UserBill::findOne(['id' => $this->get('id')]);
        if (empty($bill)) {
            throw new NotFoundHttpException('没有找到账单。');
        }
        $bill->money = $this->get('money');
        $bill->save();
        ManagerLog::info($this->manager->id, '修改用户账单金额', print_r($this->get(), true));

        return [];
    }
    //调整代理商金额
    public function actionModifyAgentMoney(){
        if(!$this->manager->can('user/modify-agent-money')){
            throw new Exception("没有权限");
        }

        $account = AgentAccount::findOne(['id'=>$this->get('id')]);
        if(empty($account)){
            throw new NotFoundHttpException('没有找到代理商');
        }

        if($this->get('money') == 0){
            $account->money = $account->money;
            $account->save();
        }else{
            $money = $this->get('money');
            $account->money = $account->money + $money;
            $account->save();
            $moneychange = new MoneyChange();
            $moneychange->money_change = $money;
            $moneychange->left_money = $account->money;
            $moneychange->recharge_number = '----------';
            $moneychange->order_no = date('YmdHis').rand(1000, 9999);
            $moneychange->create_time = time();
            $moneychange->money_source = 2;
            $moneychange->agent_id = $account->agent_id;
            $moneychange->save();
            ManagerLog::info($this->manager->id, '调整代理商金额', print_r($this->get(), true));
            return [];
        }
        
        
    }
    //调整用户预存金额
    public function actionModifyUserMoney(){
        if(!$this->manager->can('user/modify-user-money')){
            throw new Exception("没有权限");
        }
        $account = UserAccount::findOne(['id'=>$this->get('id')]);
        if(empty($account)){
            throw new NotFoundHttpException('没有找到用户');
            
        }
        if(empty($this->get('money'))){
            $account->money = $account->money;
            $account->save();
            return [];
        }else{
            $account->money = $this->get('money');
            $account->save();
        }
        ManagerLog::info($this->manager->id,'调整用户金额',print_r($this->get(),true));
        return [];
    }
    //修改代理账单金额
    public function actionModifyCommissionMoney(){
        $agent_bill = AgentBill::findOne(['id'=>$this->get('id')]);
        if(empty($agent_bill)){
            throw new Exception('没有找到账单');
            
        }
        $agent_bill->money = $this->get('money');
        $agent_bill->save();
        ManagerLog::info($this->manager->id,'修改代理账单金额',print_r($this->get(),true));
        return [];
    }
    /**
     * 发布用户账单AJAX接口
     * @return array
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionPublishBill()
    {
        if (!$this->manager->can('user/bill-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $bill = UserBill::findOne(['id' => $this->get('id')]);
        if (empty($bill)) {
            throw new NotFoundHttpException('没有找到账单。');
        }
        $bill->status = UserBill::STATUS_PUBLISH;
        $bill->save();
        ManagerLog::info($this->manager->id, '发布用户账单', print_r($bill->attributes, true));

        return [];
    }
    //发布代理账单
    public function actionPublishCommissionBill(){
        $agent_bill = AgentBill::findOne(['id'=>$this->get('id')]);
        if(empty($agent_bill)){
            throw new Exception('没有找到账单');
            
        }
        $agent_bill->status = AgentBill::STATUS_PUBLISH;
        $agent_bill->save();
        $account = AgentAccount::findOne(['agent_id'=>$agent_bill->agent_id])->getAttribute('money');
        $account_money = $account + $agent_bill->money;

        $money_change = new MoneyChange();
        $money_change->money_change = $agent_bill->money;
        $money_change->left_money = $account_money;
        $money_change->order_no = date('Ymd').time();
        $money_change->create_time = time();
        $money_change->agent_id = $agent_bill->agent_id;
        $money_change->money_source = MoneyChange::STATUS_PROFIT;
        $money_change->save();
        ManagerLog::info($this->manager->id,'发布代理账单',print_r($agent_bill->attributes,true));
        return [];
    }
    /**
     * 添加修改用户
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws Exception
     */
    public function actionUserEdit()
    {
        if (!$this->manager->can('user/user-edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        if (!empty($id)) {
            $user = User::findOne(['id' => $id]);
            if (empty($user)) {
                throw new NotFoundHttpException('没有找到用户信息。');
            }
        } else {
            $user = new User();
            $user->status = User::STATUS_OK;
            $user->create_time = time();
        }
        if ($user->load($this->post())) {
            if (!empty($user->password) && !preg_match('/^\$2y/', $user->password)) {
                $user->password = Yii::$app->security->generatePasswordHash($user->password);
            }
            if ($user->save()) {
                ManagerLog::info($this->manager->id, '保存用户', print_r($user->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/admin/user/user-list']),
                    'txt' => '用户列表'
                ]));
            }
        }
        return $this->render('user_edit', [
            'user' => $user,
        ]);
    }

    /**
     * 用户详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUserView()
    {
        if (!$this->manager->can('user/user-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $user = User::findOne(['id' => $id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户信息。');
        }
        return $this->render('user_view', [
            'user' => $user,
        ]);
    }

    /**
     * 用户设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUserConfig()
    {
        if (!$this->manager->can('user/user-edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $user = User::findOne(['id' => $id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户。');
        }
        return $this->render('user_config', [
            'user' => $user,
        ]);
    }

    /**
     * 保存用户配置AJAX接口
     * @return array
     */
    public function actionSaveUserConfig()
    {
        if (!$this->manager->can('user/user-edit')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $uid = $this->get('uid');
        $k = $this->get('k');
        $v = $this->get('v');
        $user = User::findOne(['id' => $uid]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        if (empty($k)) {
            return ['error' => 'SERVER', 'message' => '参数错误，没有找到键。'];
        }
        $r = UserConfig::setConfig($user->id, $k, $v);
        if (!$r) {
            return ['error' => 'SERVER', 'message' => '无法保存用户配置。'];
        }
        ManagerLog::info($this->manager->id, '保存用户配置', print_r($this->get(), true));
        return [];
    }

    /**
     * 重置用户密码AJAX接口
     * @return array
     * @throws Exception
     */
    public function actionResetUserPassword()
    {
        if (!$this->manager->can('user/user-edit')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $id = $this->get('id');
        $user = User::findOne(['id' => $id]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        $password = Util::randomStr(6, 1);
        $user->password = Yii::$app->security->generatePasswordHash($password);
        $user->save(false);
        ManagerLog::info($this->manager->id, '重置用户密码', $user->id);
        return ['new_password' => $password];
    }

    /**
     * 用户日志
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserLogList()
    {
        if (!$this->manager->can('user/user-log')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = UserLog::find()->alias('log');
        $query->joinWith('user user');
        $query->andFilterWhere(['like', 'user.username', $this->get('search_username')]);
        $query->andFilterWhere(['log.type' => $this->get('search_type')]);
        $query->andFilterWhere(['like', 'log.info', $this->get('search_info')]);
        $search_start_date = $this->get('search_start_date');
        if (!empty($search_start_date)) {
            $query->andFilterWhere(['>=', 'log.time', strtotime($search_start_date)]);
        }
        $search_end_date = $this->get('search_end_date');
        if (!empty($search_end_date)) {
            $query->andFilterWhere(['<', 'log.time', strtotime($search_end_date) + 86400]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('log.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $logList = $query->all();
        return $this->render('user_log_list', [
            'logList' => $logList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 用户日志详情AJAX接口
     * @return array
     */
    public function actionUserLogDetail()
    {
        if (!$this->manager->can('user/user-log')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $id = $this->get('id');
        $log = UserLog::findOne(['id' => $id]);
        if (empty($log)) {
            return ['error' => 'SERVER', 'message' => '没有找到日志信息。'];
        }
        return [
            'log' => $log->getAttributes(['id', 'info', 'time', 'data']),
        ];
    }

    /**
     * 用户套餐设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUserPackage()
    {
        if (!$this->manager->can('user/user-package')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $user = User::findOne(['id' => $this->get('id')]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户。');
        }
        if (empty($user->agent_id)) { // 没有代理商直接获取系统套餐
            $packageList = Package::find()->all();
        } else { // 获取代理商的套餐
            $packageList = [];
            /** @var AgentPackage $agentPackage */
            foreach (AgentPackage::find()->andWhere(['agent_id' => $user->agent_id])->each() as $agentPackage) {
                $packageList[] = $agentPackage->package;
            }
        }
        $userPackageMap = [];
        /** @var UserPackage $userPackage */
        foreach (UserPackage::find()->andWhere(['uid' => $user->id])->each() as $userPackage) {
            $userPackageMap[$userPackage->package_id] = $userPackage;
        }
        return $this->render('user_package', [
            'user' => $user,
            'packageList' => $packageList,
            'userPackageMap' => $userPackageMap,
        ]);
    }

    /**
     * 保存用户价格AJAX接口
     * @return array
     */
    public function actionSaveUserPackage()
    {
        if (!$this->manager->can('user/user-package')) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $uid = $this->get('uid');
        $packageId = $this->get('package_id');
        $usePool = $this->get('use_pool');
        $costPrice = $this->get('cost_price');

        $user = User::findOne(['id' => $uid]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        $package = Package::findOne(['id' => $packageId]);
        if (empty($package)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
        if (empty($costPrice) || $costPrice < $package->price) {
            return ['error' => 'SERVER', 'message' => '价格错误。'];
        }
        $userPackage = UserPackage::findOne(['uid' => $user->id, 'package_id' => $package->id]);
        if (empty($userPackage)) {
            $userPackage = new UserPackage();
            $userPackage->uid = $user->id;
            $userPackage->package_id = $package->id;
        }
        $userPackage->use_pool = $usePool;
        $userPackage->cost_price = $costPrice;
        $userPackage->save();
        ManagerLog::info($this->manager->id, '保存用户价格', print_r($this->get(), true));
        return [];
    }

    /**
     * 用户分析统计
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUserAnalyze()
    {
        if (!$this->manager->can('user/user-analyze')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $user = User::findOne(['id' => $id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户信息。');
        }
        // 总数量
        $amount = Card::find()->andWhere(['uid' => $user->id])->count();
        // 状态统计
        $statusCount = Card::find()
            ->asArray()
            ->select([
                'status' => 'status',
                'amount' => new Expression('COUNT(0)'),
            ])
            ->andWhere(['uid' => $user->id])
            ->groupBy('status')
            ->all();
        array_walk($statusCount, function (&$item) {
            $item['status'] = KeyMap::getValue('card_status', $item['status']);
        });
        $statusCount = ArrayHelper::map($statusCount, 'status', 'amount');
        return $this->render('user_analyze', [
            'user' => $user,
            'amount' => $amount,
            'statusCount' => $statusCount,
        ]);
    }
    /**
     * 代理商IMEI 列表
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionBindImeiList(){

        $query = BindImei::find()->alias('i');
        //$query->andFilterWhere(['use rname'=>$this->get('search_username')]);
        $query->joinWith('agent a');
        $query->andFilterWhere(['like', 'a.username', $this->get('search_username')]);
        $query->andFilterWhere(['like', 'i.imei', $this->get('search_imei')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        //echo $query->createCommand()->rawSql;exit;
        $agentList = $query->all();
        /*$money = '0';
        echo "<pre>";
        print_r($agentList);exit;*/
        return $this->render('bind_imei_list', [
            'agentList' => $agentList,
            'pagination' => $pagination,
        ]);
    }
    /**
     * 添加修改代理商IMEI
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionBindImei()
    {

        $id = $this->get('id');
        $model = new BindImei();
        $model->setAttributes($this->get());

        if (!empty($id)) {
            $bind = BindImei::findOne(['id' => $id]);

            if (empty($bind)) {
                throw new NotFoundHttpException('没有找到绑定信息信息。');
            }
        } else {
            $bind = new BindImei();
        }
        if ($bind->load($this->post())) {

            $bindForm = Yii::$app->request->post("BindImei");
            $bind->agent_id = Agent::findOne(['username' => $bindForm['username'], 'status' => Agent::STATUS_OK])->id;
            $bind->iccid = $bindForm['iccid'];
            $bind->imei = $bindForm['imei'];
            $bind->create_time = time();
            if($bind->save()){
                ManagerLog::info($this->manager->id, '保存卡', print_r($bind->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/admin/user/bind-imei-list']),
                    'txt' => '绑定列表'
                ]));
            }

        }
        return $this->render('bind_imei', [
            'model' => $model,
            'bind' => $bind,
        ]);
    }
    /**
     * 添加修改代理商IMEI
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionBindImei2()
    {
        /*if (!$this->manager->can('outbound/menu')) {
            throw new ForbiddenHttpException('没有权限。');
        }*/
        $id = $this->get('id');
        $model = new OrderForm();
        $model->setAttributes($this->get());

        if (!empty($id)) {
            $order = Order::findOne(['id' => $id]);
            $order->create_time = time();
            if (empty($order)) {
                throw new NotFoundHttpException('没有找到卡信息。');
            }
            if(!empty($order->agent)){
                $model->user_type='agent';
                $order->uid="";
                $model->username = OrderForm::nameget("agent",$order->agent);
            }else{
                $model->user_type='user';
                $order->agent="";
                $model->username = OrderForm::nameget("user",$order->uid);
            }
        } else {
            $order = new Order();
            $order->create_time = time();
            $order->orderno = Outbound::generateBatchNo();
        }
        $orderForm = Yii::$app->request->post("OrderForm");
        $uid = OrderForm::useridget($orderForm['user_type'],$orderForm['username']);
        if($orderForm['user_type']=='user'){
            $order->uid = $uid;
            $order->agent="";
        }else{
            $order->agent = $uid;
            $order->uid = "";
        }

        $order->status = 0;
        //print_r($model);
        //if ($order->load($this->post())  && $model->dispatch() && $order->save() ) {
        if ($order->load($this->post()) && $order->save() ) {
            ManagerLog::info($this->manager->id, '保存卡', print_r($order->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin//order-list']),
                'txt' => '订单列表'
            ]));
        }
        return $this->render('order_edit', [
            'order' => $order,
            'model' => $model,
        ]);
    }
}
